package com.hz.api.admin;

import com.hz.api.admin.adapter.ResultMessage;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @author liusu
 */
@Slf4j
@Component
public class MessageServer implements CommandLineRunner {

    private ChannelFuture channelFuture;

    @Override
    public void run(String... args) throws Exception {
        try {
            log.info("启动消息接收服务端...");
            EventLoopGroup bossGroup = new NioEventLoopGroup(1);
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            channel.pipeline().addLast(new LineBasedFrameDecoder(1048576))
                                    .addLast(new StringDecoder());
                            pipeline.addLast(new ResultMessage());
                        }
                    });
            channelFuture = bootstrap.bind(19000).sync();
            log.info("启动消息接收服务端成功...");
        }catch (Throwable e){
            if (channelFuture != null && channelFuture.channel() != null) {
                channelFuture.channel().close();
            }
        }
    }
}